<?php
/**
 * Created by PhpStorm.
 * User: apple
 * Date: 17/2/21
 * Time: 14:19
 */
namespace Admin\Controller;
use Common\Controller\AdminbaseController;

class LectureController extends AdminbaseController{

    //讲师列表
    public function index(){
        $where=array();
        $keyword=I("keyword");
        $where['status']=0;
        if(!empty($keyword)){
            $where["name"]=array("like","%$keyword%");
        }
        M('lecture')->where($where);
        $count=M('lecture')->count();
        $page=$this->page($count,20);

        $posts=M('lecture')->where($where)->limit($page->firstRow,$page->listRows)->select();
        $this->assign("page",$page->show());
        $this->assign("formget",array_merge($_GET,$_POST));
        $this->assign("posts",$posts);

        $this->display();
    }

    //添加讲师
    public function add(){
        $this->display();
    }

    public function add_post(){
        $data['create_at']=date("Y-m-d h:i:s",time());
        if(IS_POST){
            if (M('lecture')->create()!==false) {
                if (M('lecture')->add($_POST,$data)!==false) {
                    $this->success("添加成功！", U("Lecture/index"));
                } else {
                    $this->error("添加失败！");
                }
            } else {
                $this->error(M('lecture')->getError());
            }
        }
    }

    //修改讲师
    public function edit(){
        $id=I('id');
        $info=M('lecture')->where("lecture_id=$id")->find();
        $this->assign('info',$info);
        $this->display();
    }

    public function edit_post(){
        $lecture_id=I('lecture_id');
        if(IS_POST){
            //如果未选择图片
            if(empty($_POST['head'])){
                $data['name']=$_POST['name'];
                $data['intro']=$_POST['intro'];
                $result=M('lecture')->where("lecture_id=$lecture_id")->save($data);
                if($result!==false){
                    $this->success("保存成功！",U("Lecture/index"));
                }else {
                    $this->error("保存失败！");
                }
            }else{
                $result=M('lecture')->where("lecture_id=$lecture_id")->save($_POST);
                if ($result!==false) {
                    $this->success("保存成功！",U("Lecture/index"));
                } else {
                    $this->error("保存失败！");
                }
            }
        }
    }

    //删除讲师
    public function delete(){
        $id=I('id');
        //判断该讲师是否有教程系列
        $count=M('course_series')->where("lecture_id=$id")->count();
        if($count>0){
            //逻辑删除
            $result=M('lecture')->where("lecture_id=$id")->save(array('status'=>1));
        }else{
            //物理删除
            $result=M('lecture')->delete($id);
        }
        if($result!==false){
            exit(json_encode(array("status"=>true,"message"=>"删除成功")));
        }else{
            exit(json_encode(array("status"=>false,"message"=>"删除失败")));
        }
    }

}